import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../common/index.dart';
import 'index.dart';

class SettingPage extends GetView<SettingController> {
  const SettingPage({super.key});

  // 主视图
  Widget _buildView() {
    final userService = Get.find<UserService>();
    // 检查用户数据是否存在
    if (userService.user.value == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "无法获取用户数据",
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: Colors.black,
              ),
            ),
            SizedBox(height: 20.h),
            ElevatedButton(
              onPressed: () {
                // 尝试重新加载用户数据
                UserModel? currentUser = userService.get_now_user();
                if (currentUser != null) {
                  controller.update(["setting"]);
                } else {
                  // 如果仍然无法获取用户数据，可以导航到登录页面
                  RouteUtil.go(RouteNames.login);
                }
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Color(0xFFCDFF5F),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.r),
                ),
              ),
              child: Text(
                "重新加载",
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w400,
                  color: Colors.black,
                ),
              ),
            ),
          ],
        ),
      );
    }

    return Column(
      children: [
        SizedBox(height: 55.h),
        Row(
          children: [
            SizedBox(width: 24.w),
            InkWell(
              onTap: () => RouteUtil.pop(),
              child: Container(
                height: 40.h,
                width: 40.w,
                padding: EdgeInsets.all(10.r),
                decoration: BoxDecoration(
                  color: Colors.black,
                  borderRadius: BorderRadius.circular(10.r),
                ),
                child: SvgPicture.asset(
                  AssetsImages.back,
                  width: 20.w,
                  height: 20.h,
                  color: Color(0xFFCDFF5F),
                ),
              ),
            ),
            Spacer(),
            Text(
              "Set Up",
              style: TextStyle(
                fontSize: 24.sp,
                fontWeight: FontWeight.w900,
                color: Colors.black,
              ),
            ),
            Spacer(),
            SizedBox(width: 64.w),
          ],
        ),
        SizedBox(height: 48.h),
        Container(
          width: 85.w,
          height: 85.h,
          decoration: BoxDecoration(color: Color(0xFFCDFF5F)),
          child: Stack(
            children: [
              Positioned(
                top: 2.h,
                left: 2.w,
                child: InkWell(
                  onTap: () => controller.update_avatar(),
                  child: Container(
                    width: 70.w,
                    height: 70.h,
                    decoration: BoxDecoration(color: Colors.black),
                    child: Center(
                      child: Obx(() {
                        final user = userService.user.value;
                        // 显示加载指示器或头像
                        if (controller.is_avatar_uploading.value) {
                          return CircularProgressIndicator(
                            color: Color(0xFFCDFF5F),
                            strokeWidth: 3.w,
                          );
                        }
                        // 如果有头像文件路径，则从本地文件加载图像
                        if (user?.avatar_image != null &&
                            user!.avatar_image!.isNotEmpty) {
                          try {
                            return CircleAvatar(
                              radius: 30.r,
                              backgroundImage: ImagePath().get_avatar_image(
                                user.avatar_image!,
                              ),
                            );
                          } catch (e) {
                            debugPrint('加载头像失败: $e');
                          }
                        }
                        // 默认使用资源文件中的头像
                        return CircleAvatar(
                          radius: 30.r,
                          backgroundImage: AssetImage(AssetsImages.bob),
                        );
                      }),
                    ),
                  ),
                ),
              ),
              Positioned(
                bottom: 2.h,
                right: 2.w,
                child: InkWell(
                  onTap: () => controller.update_avatar(),
                  child: Container(
                    width: 24.w,
                    height: 24.h,
                    decoration: BoxDecoration(
                      color: Color(0xFFCDFF5F),
                      border: Border.all(color: Colors.black, width: 1.w),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.camera_enhance_sharp,
                      color: Colors.black,
                      size: 12.sp,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 60.h),
        Container(
          width: 320.w,
          height: 200.h,
          decoration: BoxDecoration(
            color: Color(0xff1E1E1E).withOpacity(0.6),
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Column(
            children: [
              SizedBox(height: 20.h),
              _buildSettingItem("Name & Password", () {
                controller.change_name_or_password();
              }),
              SizedBox(height: 18.h),
              _buildSettingItem("Privacy Policy", () {
                final Uri url = Uri.parse(
                  "https://www.freeprivacypolicy.com/live/3c2c565a-da96-4bda-9fd3-51e2625c89b5",
                );
                launchUrl(url, mode: LaunchMode.inAppWebView);
              }),
              SizedBox(height: 18.h),
              _buildSettingItem("Terms Of service", () {
                final Uri url = Uri.parse(
                  "https://www.freeprivacypolicy.com/live/2d8a19f6-2eb8-4536-8ab9-0b1789c0ac17",
                );
                launchUrl(url, mode: LaunchMode.inAppWebView);
              }),
              SizedBox(height: 18.h),
              _buildSettingItem("Delete Account", () {
                controller.delete_user();
              }),
              SizedBox(height: 18.h),
            ],
          ),
        ),
        SizedBox(height: 85.h),
        Container(
          width: 340.w,
          height: 55.h,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFFFEED01), Color(0xFFB3A1FE)],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              stops: [0.0, 1.0],
            ),
            borderRadius: BorderRadius.circular(75.r),
            boxShadow: [
              BoxShadow(
                color: Color.fromRGBO(69, 43, 108, 0.25),
                offset: Offset(0, 4),
                blurRadius: 4,
              ),
            ],
          ),
          child: ElevatedButton(
            onPressed: () {
              controller.logout();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.transparent,
              shadowColor: Colors.transparent,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(30.r),
              ),
            ),
            child: Text(
              'Log Out',
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
                color: Colors.white,
              ),
            ),
          ),
        ),

        Spacer(),
        SizedBox(width: 100.h),
      ],
    );
  }

  Widget _buildSettingItem(String title, VoidCallback onTap) {
    return InkWell(
      onTap: onTap,
      child: Container(
        width: 300.w,
        height: 24.h,
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(10.r),
        ),
        child: Row(
          children: [
            Text(
              title,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
                color: Colors.white,
              ),
            ),
            Spacer(),
            Icon(Icons.arrow_forward_ios, color: Colors.white, size: 14.sp),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SettingController>(
      init: SettingController(),
      id: "setting",
      builder: (_) {
        return Scaffold(
          resizeToAvoidBottomInset: false,
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(AssetsImages.settingBg),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(top: false, bottom: false, child: _buildView()),
          ),
        );
      },
    );
  }
}
